package com.hd.manager.controller;

import com.hd.appcommon.constant.OrgMemberConstant;
import com.hd.appcommon.entity.Teacher;
//import com.hd.appcommon.service.IOrgMemberLoginRecordService;
import com.hd.appcommon.entity.User;
import com.hd.appcommon.utils.SecretUtils;
import com.hd.appcommon.utils.VertifyCodeUtils;
import com.hd.hdxgddcommon.controller.AbstractController;
import com.hd.hdxgddcommon.entity.dto.ResultDto;
import com.hd.hdxgddcommon.utils.IPUtil;
import com.hd.hdxgddcommon.utils.JwtUtil;
import com.hd.hdxgddcommon.utils.StringUtils;
import com.hd.manager.shiro.ShiroUtils;
import com.hd.manager.shiro.sevice.IShiroAdminService;
import com.hd.manager.util.TextMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class AuthController extends AbstractController {

//    @Autowired
//    private IOrgMemberLoginRecordService loginRecordService;


    @Autowired
    private IShiroAdminService shiroAdminService;

    @Autowired
    private RedisTemplate redisTemplate;


    // 生成验证码
    @PostMapping("/getCode")
    public ResultDto getImageCode(HttpServletRequest request, String num, String phone) throws IOException {

        User teacher = shiroAdminService.getByAccount(phone, null);
        if ( null == teacher)
            return fail("权限不够,无法登陆");

        // 1. 使用工具类生成验证码
        String code = VertifyCodeUtils.generateVerifyCode(4);
        redisTemplate.opsForValue().set("VertifyCode_" + num, code ,2 * 60, TimeUnit.SECONDS); // 存放生成的验证码
        // 2. 将验证码放入ServletContext作用域
        request.getServletContext().setAttribute("code", code);

        Map<String, String> sendMessage = TextMessageUtil.sendMessage(phone, code);

        return sendMessage.get("success") != null ? success( sendMessage.get("success")) : fail(sendMessage.get("fail"));
    }


    //登录
    @PostMapping("/login/submit")
    public ResultDto auth(String account, String password, String code, String num, HttpServletRequest request) {
        log.info("开始登录");
        String host = IPUtil.getRealIp(request);
        String message = null;
        User token = null;

        if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(num)){
            String validate_code = (String) redisTemplate.opsForValue().get("VertifyCode_" + num);

            if (StringUtils.isBlank(validate_code)){
                return new ResultDto(0, "验证码已过期或已使用", null);
            }
            if(!code.equals(validate_code)){
                message = "验证码输入错误!";
                return new ResultDto(0, message, null);
            }
            redisTemplate.opsForValue().set("VertifyCode_" + num, ""); // 存放生成的验证码
            token = shiroAdminService.getByAccount(account,null);
        }else {
            // 15336588286 29011
            if (StringUtils.isBlank(account, password)) {
                message = "账号密码不能为空!";
            }

            // aes解码
            password = SecretUtils.desEncrypt(password);
            //加密,与数据库已加密的字符串比对
            String encryptPassword =  ShiroUtils.getEncryptPassword(account, password);
            token = shiroAdminService.getByAccount(account, encryptPassword);
            System.out.println("对比成功");
        }

        if (null == token) {
            message = "账号密码不正确";
        }

        if (StringUtils.isNotBlank(message)){
            //登录失败日志
//            loginRecordService.asyncSave("", account, host,null,
//                    OrgMemberConstant.LOGIN_STATUS.FAIL, OrgMemberConstant.LOGIN_TYPE.BACKEND, message);
            ResultDto result = new ResultDto(0, message, null);
            return result;
        }

        Map<String, Object> p = new HashMap<>();
        p.put("id", token.getId());
        String jwt = JwtUtil.createJWT(1000 * 60 * 60 , p, token.getDdid(), JwtUtil.KEY);

//        //登录成功日志
//        loginRecordService.asyncSave(String.valueOf(token.getId()), token.getName(), host, token.getPhone(),
//                OrgMemberConstant.LOGIN_STATUS.SUCCESS, OrgMemberConstant.LOGIN_TYPE.BACKEND, "登录成功");

        Map<String,Object> res=new HashMap<>();
        res.put("jwt",jwt);
        res.put("username",token.getName());

        System.out.println("登录成功");
        return success(1, "登录成功", res);
    }

    @PostMapping("/login/tokenNum")
    public ResultDto authT(String token) {

        Integer times = (Integer) redisTemplate.opsForValue().get("submit_"+token);
        boolean sign = Boolean.TRUE;
        if (null == times){
            redisTemplate.opsForValue().set("submit_"+token, 1 ,60 * 60  , TimeUnit.SECONDS);
        }else {
            sign = false;
        }
        return  sign? success(1,"登陆成功", sign) : fail(0, "登陆失败", sign);
    }

    //修改密码
//    @RequestMapping("/change/password")
//    public ResultDto changePassword(@RequestParam String newPw) {
//
//        Teacher token = TokenManager.getToken();
//        String TeacherId = Integer.toString(token.getId());
//        Teacher orgAdmin = teacherService.getById(TeacherId);
//        String phone = token.getPhone();
//        newPw = ShiroUtils.getEncryptPassword(phone,newPw);
//        if (orgAdmin != null) {
//            orgAdmin.setPassword(newPw);
//            orgAdmin.setModifyTime(new Date());
//            return   teacherService.updateById(orgAdmin)? success() : fail();
//        } else {
//            return fail("该用户不存在");
//        }
//    }

    @RequestMapping("/logout")
    public ResultDto logout() {
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception e) {
            return fail();
        }
        return success("/");
    }
}
